package com.atwork.wuhua.utils.HttpUtil;

import com.atwork.wuhua.APIFunction;
import com.atwork.wuhua.base.MyApplication;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/3/13 0013.
 */

public class RetrofitFactory {
    private static APIFunction mAPIFunction;

    private RetrofitFactory() {
        int cacheSize = 10 * 1024 * 1024;// 10 MiB
        Cache cache = new Cache(MyApplication.getMyApplication().getCacheDir(), (long) cacheSize);
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)
                .readTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)
                .writeTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)
//                .addInterceptor(InterceptorUtil.tokenInterceptor())
                .addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器
                .cache(cache)

                .build();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(HttpConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))//添加gson转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
                .client(mOkHttpClient)
                .build();
        mAPIFunction = mRetrofit.create(APIFunction.class);
    }

    //    private static volatile RetrofitFactory mRetrofitFactory = null;
//
//    public static RetrofitFactory getInstence1() {
//        if (mRetrofitFactory == null) {
//            synchronized (RetrofitFactory.class) {
//                if (mRetrofitFactory == null) {
//                    mRetrofitFactory = new RetrofitFactory();
//                }
//            }
//        }
//        return mRetrofitFactory;
//    }
    public static RetrofitFactory getInstence() {

        return SingletonHolder.sInstance;
    }

    private static class SingletonHolder {
        private static final RetrofitFactory sInstance = new RetrofitFactory();
    }

    public APIFunction API() {
        return mAPIFunction;
    }
}
